package com.example.myapplication;

import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * 书籍管理页面
 */
public class BookManagementActivity extends AppCompatActivity {
    private EditText etBookNumber;
    private EditText etBookName;
    private Button btnAdd;
    private Button btnDelete;
    private Button btnUpdate;
    private Button btnQuery;
    private RecyclerView recyclerView;
    
    private BookAdapter adapter;
    private BookDatabaseHelper dbHelper;
    private String userEmail; // 当前用户邮箱
    private Book selectedBook; // 当前选中的书籍

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_management);

        // 获取用户邮箱
        userEmail = getIntent().getStringExtra("user_email");
        if (TextUtils.isEmpty(userEmail)) {
            Toast.makeText(this, "用户信息错误", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化数据库
        dbHelper = new BookDatabaseHelper(this);

        // 初始化控件
        initViews();

        // 设置RecyclerView
        setupRecyclerView();

        // 设置按钮点击事件
        setupButtons();

        // 初始加载全部书籍
        loadAllBooks();
    }

    private void initViews() {
        etBookNumber = findViewById(R.id.et_book_number);
        etBookName = findViewById(R.id.et_book_name);
        btnAdd = findViewById(R.id.btn_add);
        btnDelete = findViewById(R.id.btn_delete);
        btnUpdate = findViewById(R.id.btn_update);
        btnQuery = findViewById(R.id.btn_query);
        recyclerView = findViewById(R.id.rv_books);
    }

    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BookAdapter();
        recyclerView.setAdapter(adapter);

        // 设置列表项点击事件
        adapter.setOnBookClickListener(book -> {
            selectedBook = book;
            etBookNumber.setText(book.getBookNumber());
            etBookName.setText(book.getBookName());
            Toast.makeText(this, "已选中：" + book.getBookName(), Toast.LENGTH_SHORT).show();
        });
    }

    private void setupButtons() {
        // 添加按钮
        btnAdd.setOnClickListener(v -> addBook());

        // 删除按钮
        btnDelete.setOnClickListener(v -> deleteBook());

        // 修改按钮
        btnUpdate.setOnClickListener(v -> updateBook());

        // 查询按钮
        btnQuery.setOnClickListener(v -> queryBooks());
    }

    /**
     * 添加书籍
     */
    private void addBook() {
        String bookNumber = etBookNumber.getText().toString().trim();
        String bookName = etBookName.getText().toString().trim();

        if (TextUtils.isEmpty(bookNumber)) {
            Toast.makeText(this, "请输入书号", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(bookName)) {
            Toast.makeText(this, "请输入书名", Toast.LENGTH_SHORT).show();
            return;
        }

        Book book = new Book(bookNumber, bookName, userEmail);
        long result = dbHelper.addBook(book);

        if (result > 0) {
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
            clearInputs();
            loadAllBooks();
        } else {
            Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 删除书籍
     */
    private void deleteBook() {
        if (selectedBook == null) {
            Toast.makeText(this, "请先选择要删除的书籍", Toast.LENGTH_SHORT).show();
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除《" + selectedBook.getBookName() + "》吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    int result = dbHelper.deleteBook(selectedBook.getId(), userEmail);
                    if (result > 0) {
                        Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                        clearInputs();
                        selectedBook = null;
                        loadAllBooks();
                    } else {
                        Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 修改书籍
     */
    private void updateBook() {
        if (selectedBook == null) {
            Toast.makeText(this, "请先选择要修改的书籍", Toast.LENGTH_SHORT).show();
            return;
        }

        String bookNumber = etBookNumber.getText().toString().trim();
        String bookName = etBookName.getText().toString().trim();

        if (TextUtils.isEmpty(bookNumber)) {
            Toast.makeText(this, "请输入书号", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(bookName)) {
            Toast.makeText(this, "请输入书名", Toast.LENGTH_SHORT).show();
            return;
        }

        selectedBook.setBookNumber(bookNumber);
        selectedBook.setBookName(bookName);

        int result = dbHelper.updateBook(selectedBook);
        if (result > 0) {
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
            clearInputs();
            selectedBook = null;
            loadAllBooks();
        } else {
            Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 查询书籍
     */
    private void queryBooks() {
        String bookNumber = etBookNumber.getText().toString().trim();
        String bookName = etBookName.getText().toString().trim();

        // 空查询显示全部书籍
        List<Book> books = dbHelper.queryBooks(bookNumber, bookName, userEmail);
        adapter.setBooks(books);

        if (books.isEmpty()) {
            Toast.makeText(this, "未找到相关书籍", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "找到 " + books.size() + " 本书籍", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 加载全部书籍
     */
    private void loadAllBooks() {
        List<Book> books = dbHelper.queryBooks("", "", userEmail);
        adapter.setBooks(books);
    }

    /**
     * 清空输入框
     */
    private void clearInputs() {
        etBookNumber.setText("");
        etBookName.setText("");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}
